package middleware

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	ginfox "westarry/gin-fox/gin-fox"
	requestLogger "westarry/gin-fox/gin-fox/logger/requestLogger"

	"github.com/gin-gonic/gin"
)

func InitAuth(c *gin.Context) {
	realUrl := strings.Split(c.Request.RequestURI, "?")[0]
	l := requestLogger.InitLogger()
	l.I.Printf("%v:%v%v", c.Request.Method, c.Request.Host, realUrl)
	defer func() {
		recover()
	}()
	authRule, _ := ginfox.Gc.R.HGet("auth_rules", realUrl)
	rule := &Rule{}
	err := json.Unmarshal([]byte(authRule), rule)
	if err != nil {
		fmt.Println("[ginfox]获取权限节点失败")
	}
	//判断请求方式
	if rule.RequestMethod!="Any"{
		if c.Request.Method!=rule.RequestMethod{
			fmt.Printf("[ginfox]%v请求方式错误\n",realUrl)
			c.AbortWithStatus(http.StatusMethodNotAllowed)
		}
	}
	
	fmt.Printf("[ginfox] %v\n", realUrl)
	c.Next()
}
